import { Link, useNavigate } from "react-router-dom";
import { Form, Input, Button, Flex } from "antd";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import styles from "./index.module.less";
import useAppStore from "@/store/appStore";
import { useLoginHooks } from "@/hooks/login";
import { useEffect, useRef } from "react";
const login = () => {
  const captchaRef = useRef<HTMLElement>(null);
  const { login, user } = useAppStore();
  const [form] = Form.useForm();
  const handleLogin = (captchaKeyId: string) => {
    const formData = form.getFieldsValue();
    login({
      account: formData.username,
      password: formData.password,
      captchaKeyId,
    });
  };
  const { initCaptcha } = useLoginHooks(handleLogin);
  const navigate = useNavigate();
  const onFinish = (_values: any) => {
    captchaRef.current?.click();
  };
  initCaptcha;
  useEffect(() => {
    console.log(user, "user");
    if (user.logined) {
      navigate("/dashboard");
    }
  }, [user]);
  return (
    <div className={styles.login}>
      <div className="login-form">
        <div className="title">登录</div>
        <Form
          form={form}
          name="login"
          initialValues={{ remember: true }}
          onFinish={onFinish}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: "请输入用户名!" }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码!" }]}
          >
            <Input
              prefix={<LockOutlined />}
              type="password"
              placeholder="密码"
            />
          </Form.Item>
          <Form.Item>
            <Link to="/forget">忘记密码</Link>
          </Form.Item>
          <div id="captchaButton" ref={captchaRef}></div>
          <div id="captcha-element"></div>
          <Form.Item>
            <Button block type="primary" htmlType="submit">
              登录
            </Button>
            <Flex justify="center" className="register-link">
              <Link to="/register">注册</Link>
            </Flex>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};
export default login;
